# -*- coding: utf-8 -*-

"""
-  filename: util/mylogs.py
-  This is a Crawl Script Util.
-  logging模块支持我们自定义封装一个新日志类
"""
import logging, time
import os.path
import sys

(BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE) = range(8)
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
COLORS = {
    'WARNING': YELLOW,
    'INFO': GREEN,
    'DEBUG': WHITE,
    'ERROR': RED,
    'CRITICAL': RED
}
LOGFORMAT_LONG = """
[%(asctime)s][%(threadName)s][%(name)s]
[%(levelname)s][%(filename)s|%(funcName)s:%(lineno)d] %(message)s
""".strip()
LOGFORMAT_SHORT1 = "[%(asctime)s][%(threadName)s][%(levelname)s][%(filename)s|%(funcName)s:%(lineno)d] %(message)s"
LOGFORMAT_SHORT0 = "[%(asctime)s][pid%(process)s][%(threadName)s] %(message)s"


def tostring(*args, **kwargs):
    # return " , ".join([str(arg) for arg in args]+[str(kwargs)])
    return " , ".join([str(arg) for arg in args])
    pass


class ColoredFormatter(logging.Formatter):
    def __init__(self, msg, use_color=True):
        logging.Formatter.__init__(self, msg)
        self.use_color = use_color

    def format(self, record):
        name = record.name
        levelname = record.levelname
        message = str(record.msg)
        funcName = record.funcName
        if self.use_color and levelname in COLORS:
            name_color = COLOR_SEQ % (30 + COLORS[levelname]) + name + RESET_SEQ
            levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ
            message_color = COLOR_SEQ % (30 + COLORS[levelname]) + message + RESET_SEQ
            funcName_color = COLOR_SEQ % (30 + COLORS[levelname]) + funcName + RESET_SEQ
            record.name = name_color
            record.levelname = levelname_color
            record.msg = message_color
            record.funcName = funcName_color
        return logging.Formatter.format(self, record)


class Logger:
    def __init__(self, loggername, logformat=LOGFORMAT_SHORT0):
        self.logger = logging.getLogger(loggername)
        self.logger.setLevel(logging.DEBUG)
        # 日志文件结构
        if not os.path.exists('logs'):
            os.makedirs('logs')
        rq = time.strftime('%Y-%m-%d', time.localtime(time.time()))  # %H%M
        log_path = 'logs/'  #
        log_name = os.getcwd() + '/' + log_path + loggername + rq + '.log'  # 文件名

        # 创建FileHandler，用于写入日志文件
        # 创建StreamHandler，用于输出到控制台
        if not self.logger.handlers:
            # 定义handler的输出格式
            color_formatter = ColoredFormatter(logformat)
            plain_formatter = logging.Formatter(logformat)
            fh = logging.FileHandler(log_name, encoding='utf-8')
            fh.setLevel(logging.DEBUG)
            fh.setFormatter(plain_formatter)
            # sys.stdout.reconfigure(encoding='utf-8')
            # sys.stderr.reconfigure(encoding='utf-8')
            ch = logging.StreamHandler(stream=sys.stderr)
            ch.setLevel(logging.DEBUG)
            ch.setFormatter(color_formatter)
            # 给logger添加handler
            self.logger.addHandler(fh)
            self.logger.addHandler(ch)

    def getLogger(self):
        return self.logger
